﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using ErrCode.Model;

namespace ErrCode.Dal
{
    public class MethodIdCenterDal : BaseDal
    {
        private static MethodIdCenterDal _instance;
        public static MethodIdCenterDal Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new MethodIdCenterDal();
                }
                return _instance;
            }
        }

        public int NextMethodId()
        {
            lock (this)
            {
                int systemId = CommonService.CurrSystemId;
                int seed = 1;
                string sql = "select * from MethodIdCenter where SystemId =@systemId";
                MethodIdCenter idCenter = ErrCodeSysConnection.Query<MethodIdCenter>(sql, new { systemId }).ToList().FirstOrDefault();
                if (idCenter != null)
                {
                    seed = idCenter.MethodSeed;
                    idCenter.MethodSeed += 1;
                    //idCenter.LastUpdate = DateTime.Now;
                    if (UpdateMethodId(idCenter) <= 0)
                    {
                        return 1;
                    }
                }
                else
                {
                    CreateMethodId();
                }
                return seed;
            }
        }

        public int UpdateMethodId(MethodIdCenter idCenter)
        {
            string sql = "UPDATE `MethodIdCenter` SET `MethodSeed`=@MethodSeed WHERE (`SystemId`=@SystemId);";
            return ErrCodeSysConnection.Execute(sql, idCenter);
        }
        public int CreateMethodId()
        {
            int systemId = CommonService.CurrSystemId;
            string sql = "INSERT INTO `MethodIdCenter` (`SystemId`, `MethodSeed`) VALUES (@systemId, '2');";
            return ErrCodeSysConnection.Execute(sql, new { systemId });
        }
    }
}
